package com.ruoyi.system.controller;

import java.util.List;
import java.util.Set;
import java.util.HashSet;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Room;
import com.ruoyi.system.service.IRoomService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import java.util.ArrayList;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 房间信息Controller
 * 
 * @author xyz
 * @date 2025-05-25
 */
@RestController
@RequestMapping("/system/room")
public class RoomController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(RoomController.class);

    @Autowired
    private IRoomService roomService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询房间信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:room:list')")
    @GetMapping("/list")
    public TableDataInfo list(Room room)
    {
        startPage();
        List<Room> list = roomService.selectRoomList(room);
        return getDataTable(list);
    }

    /**
     * 导出房间信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:room:export')")
    @Log(title = "房间信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Room room)
    {
        List<Room> list = roomService.selectRoomList(room);
        ExcelUtil<Room> util = new ExcelUtil<Room>(Room.class);
        util.exportExcel(response, list, "房间信息数据");
    }

    /**
     * 获取房间信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:room:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(roomService.selectRoomById(id));
    }

    /**
     * 新增房间信息
     */
    @PreAuthorize("@ss.hasPermi('system:room:add')")
    @Log(title = "房间信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Room room)
    {
        return toAjax(roomService.insertRoom(room));
    }

    /**
     * 修改房间信息
     */
    @PreAuthorize("@ss.hasPermi('system:room:edit')")
    @Log(title = "房间信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Room room)
    {
        return toAjax(roomService.updateRoom(room));
    }

    /**
     * 删除房间信息
     */
    @PreAuthorize("@ss.hasPermi('system:room:remove')")
    @Log(title = "房间信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(roomService.deleteRoomByIds(ids));
    }

    /**
     * 根据用户ID查询所在房间信息
     */
    @GetMapping("/searchRoomUser")
    public AjaxResult searchRoomUser(@RequestParam("userId") String userId)
    {
        if (StringUtils.isBlank(userId)) {
            return error("用户ID不能为空");
        }
        
        List<Room> rooms = roomService.selectRoomsByUserId(userId);
        return success(rooms);
    }

    /**
     * 添加业务员到房间组
     */
    @PreAuthorize("@ss.hasPermi('system:room:edit')")
    @Log(title = "房间信息", businessType = BusinessType.UPDATE)
    @PostMapping("/addSalesperson")
    public AjaxResult addSalesperson(@RequestBody Map<String, Object> params) {
        String roomId = params.get("roomId").toString();
        String salespersonUserId = params.get("salespersonUserId").toString();
        
        // 获取当前房间信息
        Room room = roomService.selectRoomById(roomId);
        if (room == null) {
            return AjaxResult.error("房间不存在");
        }
        
        // 获取业务员信息
        SysUser salesperson = userService.selectUserById(Long.parseLong(salespersonUserId));
        if (salesperson == null) {
            return AjaxResult.error("业务员不存在");
        }
        
        // 检查业务员的EE值
        // 如果EE为正常，检查该业务员是否已经在其他房间
        // 如果EE为拒绝串台，也不允许进入其他房间
        // 如果EE为申请串台，也不允许进入其他房间
        if ("正常".equals(salesperson.getEe()) || "拒绝串台".equals(salesperson.getEe()) || "申请串台".equals(salesperson.getEe())) {
            List<Room> allRooms = roomService.selectRoomList(new Room());
            for (Room r : allRooms) {
                if (r.getGroupName() != null && r.getGroupName().contains(salespersonUserId)) {
                    return AjaxResult.error("该业务员只能加入一个房间");
                }
            }
        }
        
        // 获取当前groupName
        String currentGroupName = room.getGroupName();
        String newGroupName;
        
        // 如果groupName为空，直接设置新的userId
        if (StringUtils.isBlank(currentGroupName)) {
            newGroupName = salespersonUserId;
        } else {
            // 检查用户是否已经在组中
            String[] existingUsers = currentGroupName.split(",");
            for (String userId : existingUsers) {
                if (userId.equals(salespersonUserId)) {
                    return AjaxResult.error("该业务员已在预定业务员组中");
                }
            }
            // 添加新的userId到组中
            newGroupName = currentGroupName + "," + salespersonUserId;
        }
        
        // 更新房间信息
        room.setGroupName(newGroupName);
        return toAjax(roomService.updateRoom(room));
    }

    /**
     * 移除房间组中的业务员
     */
    @PreAuthorize("@ss.hasPermi('system:room:edit')")
    @Log(title = "房间信息", businessType = BusinessType.UPDATE)
    @PostMapping("/removeywy")
    public AjaxResult removeSalesperson(@RequestBody Map<String, Object> params) {
        String roomId = params.get("roomId").toString();
        String salespersonUserId = params.get("salespersonUserId").toString();
        
        log.info("开始移除业务员，房间ID: {}, 业务员ID: {}", roomId, salespersonUserId);

        // 获取当前房间信息
        Room room = roomService.selectRoomById(roomId);
        if (room == null) {
            log.error("房间不存在，房间ID: {}", roomId);
            return AjaxResult.error("房间不存在");
        }

        // 获取当前groupName
        String currentGroupName = room.getGroupName();
        log.info("当前房间groupName: {}", currentGroupName);
        
        if (StringUtils.isBlank(currentGroupName)) {
            log.error("房间没有业务员，房间ID: {}", roomId);
            return AjaxResult.error("房间没有业务员");
        }

        // 拆分groupName，移除指定userId
        List<String> userIdList = new ArrayList<>(Arrays.asList(currentGroupName.split(",")));
        log.info("当前房间业务员列表: {}", userIdList);
        
        boolean removed = userIdList.removeIf(userId -> {
            boolean matches = userId.equals(salespersonUserId);
            log.info("比较userId: {} 与 salespersonUserId: {}, 结果: {}", userId, salespersonUserId, matches);
            return matches;
        });
        
        if (!removed) {
            log.error("业务员不在房间组中，房间ID: {}, 业务员ID: {}", roomId, salespersonUserId);
            return AjaxResult.error("该业务员不在房间组中");
        }

        // 重新拼接groupName
        String newGroupName = String.join(",", userIdList);
        log.info("更新后的groupName: {}", newGroupName);
        
        room.setGroupName(newGroupName);

        // 更新房间信息
        int rows = roomService.updateRoom(room);
        log.info("更新房间信息结果: {}", rows);
        
        return toAjax(rows);
    }

    /**
     * 根据业务员userId查询所在房间信息
     */
    @GetMapping("/searchYeWuYuanRoom")
    public AjaxResult searchYeWuYuanRoom(@RequestParam("userId") String userId) {
        if (StringUtils.isBlank(userId)) {
            return error("业务员ID不能为空");
        }
        
        log.info("查询业务员所在房间，业务员ID: {}", userId);
        
        // 查询所有房间
        List<Room> allRooms = roomService.selectRoomList(new Room());
        List<Room> resultRooms = new ArrayList<>();
        
        for (Room room : allRooms) {
            if (StringUtils.isNotBlank(room.getGroupName())) {
                // 检查业务员是否在该房间的groupName中
                String[] userIds = room.getGroupName().split(",");
                for (String roomUserId : userIds) {
                    if (roomUserId.equals(userId)) {
                        resultRooms.add(room);
                        log.info("找到业务员所在房间，房间ID: {}, 房间名: {}", room.getId(), room.getCc());
                        break;
                    }
                }
            }
        }
        
        log.info("业务员所在房间数量: {}", resultRooms.size());
        return success(resultRooms);
    }

    /**
     * 根据业务经理userId查询所在房间信息
     */
    @GetMapping("/searchYewuJingLi")
    public AjaxResult searchYewuJingLi(@RequestParam("userId") String userId) {
        if (StringUtils.isBlank(userId)) {
            return error("业务经理ID不能为空");
        }
        
        log.info("查询业务经理所在房间，业务经理ID: {}", userId);
        
        // 查询所有房间
        List<Room> allRooms = roomService.selectRoomList(new Room());
        List<Room> resultRooms = new ArrayList<>();
        
        for (Room room : allRooms) {
            // 检查业务经理是否是该房间的轮房人（通过ff字段或ee字段）
            if (userId.equals(room.getFf()) || userId.equals(room.getEe())) {
                resultRooms.add(room);
                log.info("找到业务经理所在房间，房间ID: {}, 房间名: {}", room.getId(), room.getCc());
            }
        }
        
        log.info("业务经理所在房间数量: {}", resultRooms.size());
        return success(resultRooms);
    }

    /**
     * 根据部门ID查询部门下所有用户相关的房间ID数组
     */
    @GetMapping("/searchDeptRoomMsg")
    public AjaxResult searchDeptRoomMsg(@RequestParam("deptId") Long deptId) {
        if (deptId == null) {
            return error("部门ID不能为空");
        }
        
        log.info("查询部门下所有用户相关的房间ID，部门ID: {}", deptId);
        
        try {
            // 1. 根据部门ID查询部门下的所有用户
            SysUser queryUser = new SysUser();
            queryUser.setDeptId(deptId);
            List<SysUser> deptUsers = userService.selectUserList(queryUser);
            
            if (deptUsers.isEmpty()) {
                log.info("部门下没有用户，部门ID: {}", deptId);
                return success(new ArrayList<>());
            }
            
            log.info("部门下用户数量: {}", deptUsers.size());
            
            // 2. 查询所有房间
            List<Room> allRooms = roomService.selectRoomList(new Room());
            Set<String> resultRoomIds = new HashSet<>(); // 使用Set去重房间ID
            
            // 3. 遍历部门下的每个用户，查找其相关的房间
            for (SysUser user : deptUsers) {
                String userId = user.getUserId().toString();
                String userName = user.getUserName();
                
                log.info("查询用户房间信息，用户ID: {}, 用户名: {}", userId, userName);
                
                for (Room room : allRooms) {
                    boolean isRelated = false;
                    
                    // 检查用户是否是该房间的轮房人
                    if (userId.equals(room.getFf()) || userName.equals(room.getEe())) {
                        isRelated = true;
                        log.info("用户是房间轮房人，房间ID: {}, 房间名: {}", room.getId(), room.getCc());
                    }
                    
                    // 检查用户是否在该房间的业务员组中
                    if (StringUtils.isNotBlank(room.getGroupName())) {
                        String[] userIds = room.getGroupName().split(",");
                        for (String roomUserId : userIds) {
                            if (roomUserId.equals(userId)) {
                                isRelated = true;
                                log.info("用户在房间业务员组中，房间ID: {}, 房间名: {}", room.getId(), room.getCc());
                                break;
                            }
                        }
                    }
                    
                    // 检查用户是否是该房间的订房人
                    if (userId.equals(room.getBookerId() != null ? room.getBookerId().toString() : null) || userName.equals(room.getBookerName())) {
                        isRelated = true;
                        log.info("用户是房间订房人，房间ID: {}, 房间名: {}", room.getId(), room.getCc());
                    }
                    
                    // 如果用户与房间相关，添加到结果集
                    if (isRelated) {
                        resultRoomIds.add(room.getId());
                    }
                }
            }
            
            List<String> finalResult = new ArrayList<>(resultRoomIds);
            log.info("部门下用户相关房间ID数量: {}", finalResult.size());
            
            return success(finalResult);
            
        } catch (Exception e) {
            log.error("查询部门房间信息失败，部门ID: {}", deptId, e);
            return error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 一键备份并清空房间信息
     */
    @PostMapping("/backupAndClearRoom")
    public AjaxResult backupAndClearRoom() {
        try {
            roomService.backupAndClearRoom();
            return AjaxResult.success("房间信息已备份并清空！");
        } catch (Exception e) {
            log.error("备份并清空房间信息失败", e);
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 翻台功能 - 备份房间信息到记录表并清空当前房间
     */
    @PreAuthorize("@ss.hasPermi('system:room:edit')")
    @Log(title = "房间翻台", businessType = BusinessType.UPDATE)
    @PostMapping("/flipTable/{roomId}")
    public AjaxResult flipTable(@PathVariable("roomId") String roomId)
    {
        try {
            // 获取当前房间信息
            Room room = roomService.selectRoomById(roomId);
            if (room == null) {
                return AjaxResult.error("房间不存在");
            }
            
            // 执行翻台操作
            roomService.flipTable(roomId);
            
            return AjaxResult.success("翻台成功");
        } catch (Exception e) {
            log.error("翻台失败", e);
            return AjaxResult.error("翻台失败：" + e.getMessage());
        }
    }
}
